<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue';
import useWebSocket from '../common/useWebSocket.js';
import { formatTime } from '../common/date.Utils.js';

// 状态管理
const tempUsername = ref('');
const username = ref('');
const userId = ref('');
const newMessage = ref('');
const messages = ref([]);
const onlineUsers = ref([]);

// WebSocket 初始化
const { 
  connect, 
  disconnect, 
  sendMessage: sendWsMessage, 
  isConnected 
} = useWebSocket({
  onMessage: handleMessage,
  onOpen: handleConnectionOpen,
  onClose: handleConnectionClose,
  onError: handleConnectionError
});

// 设置用户名并进入聊天
function setUsername() {
  if (tempUsername.value.trim()) {
    username.value = tempUsername.value.trim();
    connect();
  }
}

// 处理接收到的消息
function handleMessage(event) {
  console.log('收到消息', JSON.parse(event.data));
  try {
    const data = JSON.parse(event.data);
    
    switch (data.type) {
      // case 'user_connected':
      //   // 服务器返回当前用户ID
      //   userId.value = data.userId;
      //   onlineUsers.value = data.onlineUsers;
      //   addSystemMessage(`${username.value}，欢迎加入聊天！`);
      //   break;
        
      case 'new_user':
        // 新用户加入
        onlineUsers.value = data.onlineUsers;
        addSystemMessage(`${data.user.name} 加入了聊天`);
        break;
        
      case 'user_disconnected':
        // 用户离开
        onlineUsers.value = data.onlineUsers;
        addSystemMessage(`${data.user.name} 离开了聊天`);
        break;
        
      case 'chat_message':
        // 普通聊天消息
        messages.value.push(data);
        scrollToBottom();
        break;
        
      default:
        console.log('未知消息类型', data);
    }
  } catch (error) {
    console.error('解析消息失败', error);
  }
  console.log("messages.value",messages.value)
}

// 发送聊天消息
function sendMessage() {
  if (newMessage.value.trim() && isConnected.value) {
    sendWsMessage({
      type: 'chat_message',
      content: newMessage.value.trim()
    });
    newMessage.value = '';
  }
}

// 添加系统消息
function addSystemMessage(content) {
  messages.value.push({
    id: Date.now().toString(),
    type: 'system_message',
    content,
    timestamp: new Date()
  });
  scrollToBottom();
}

// 辅助函数：滚动到最新消息
function scrollToBottom() {
  setTimeout(() => {
    const messagesContainer = document.querySelector('.messages');
    if (messagesContainer) {
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
  }, 0);
}

// WebSocket事件处理
function handleConnectionOpen() {
  console.log('WebSocket连接已打开');
  // 发送用户信息
  sendWsMessage({
    type: 'user_info',
    name: username.value
  });
}

function handleConnectionClose() {
  console.log('WebSocket连接已关闭');
  addSystemMessage('连接已断开，请刷新页面重新连接');
}

function handleConnectionError(error) {
  console.error('WebSocket连接错误', error);
  addSystemMessage('连接出错，请稍后重试');
}

// 组件生命周期
onMounted(() => {
  // 页面加载时的初始化操作
});

onUnmounted(() => {
  disconnect();
});
</script>

<template>
  <div class="chat-app">
    <div class="chat-header">
      <h2>实时聊天应用</h2>
      <div v-if="!isConnected" class="connection-status disconnected">未连接</div>
      <div v-else class="connection-status connected">已连接</div>
    </div>
    
    <div class="user-setup" v-if="!username">
      <input 
        type="text" 
        v-model="tempUsername" 
        placeholder="请输入用户名"
        @keyup.enter="setUsername"
      >
      <button @click="setUsername">进入聊天</button>
    </div>
    
    <div class="chat-container" v-else>
      <div class="user-list">
        <h3>在线用户 ({{ onlineUsers.length }})</h3>
        <ul>
          <li v-for="user in onlineUsers" :key="user.id" :class="{ 'current-user': user.id === userId }">
            {{ user.name }}
            <span v-if="user.id === userId">(你)</span>
          </li>
        </ul>
      </div>
      
      <div class="message-area">
        <div class="messages">
          <div v-for="msg in messages" :key="msg.id" class="message" :class="{ 'my-message': msg.senderId === userId }">
            <div class="message-info">
              <span class="sender">{{ msg.senderName }}</span>
              <span class="time">{{ formatTime(msg.timestamp) }}</span>
            </div>
            <div class="message-content">{{ msg.content }}</div>
          </div>
        </div>
        
        <div class="message-input">
          <input 
            type="text" 
            v-model="newMessage" 
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
          />
          <button @click="sendMessage">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-app {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.connection-status {
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 14px;
}

.connected {
  background-color: #e3f2fd;
  color: #0d47a1;
}

.disconnected {
  background-color: #ffebee;
  color: #b71c1c;
}

.user-setup {
  text-align: center;
  margin: 50px auto;
  max-width: 300px;
}

.user-setup input {
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.user-setup button {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.chat-container {
  display: flex;
  gap: 20px;
  height: 600px;
}

.user-list {
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 15px;
  overflow-y: auto;
}

.user-list h3 {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ddd;
}

.user-list ul {
  list-style: none;
  padding: 0;
}

.user-list li {
  padding: 8px 5px;
  border-radius: 4px;
  margin-bottom: 5px;
}

.user-list li.current-user {
  background-color: #e8f5e9;
  font-weight: bold;
}

.message-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #fafafa;
}

.message {
  margin-bottom: 15px;
  max-width: 70%;
  animation: fadeIn 0.3s ease;
}

.message.my-message {
  margin-left: auto;
}

.message-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
}

.sender {
  font-weight: bold;
  color: #2c3e50;
}

.my-message .sender {
  color: #3498db;
}

.time {
  color: #7f8c8d;
}

.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
}

.my-message .message-content {
  background-color: #e3f2fd;
  border-color: #bbdefb;
}

.message-input {
  
  display: flex;
  padding: 10px;
  border-top: 1px solid #ddd;
  background-color: #ffffff;
}

.message-input input {
  width: 123px;
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
}

.message-input input:focus {
  border-color: #42b983;
}

.message-input button {
  margin-left: 10px;
  /* padding: 10px 20px; */
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.message-input button:hover {
  background-color: #359268;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>
